package com.example.zhangxin.myhuatuob2b.fragment.home.home;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zhangxin.myhuatuob2b.R;
import com.example.zhangxin.myhuatuob2b.activity.GoodsDetailsActivity;
import com.example.zhangxin.myhuatuob2b.activity.GoodsListFragmentManager;
import com.example.zhangxin.myhuatuob2b.activity.SearchActivity;
import com.example.zhangxin.myhuatuob2b.activity.SubjectActivity;
import com.example.zhangxin.myhuatuob2b.activity.TwoTypeActivity;
import com.example.zhangxin.myhuatuob2b.adapter.HeadImageAdapter;
import com.example.zhangxin.myhuatuob2b.adapter.HomeGoodsMyGridViewListAdapter;
import com.example.zhangxin.myhuatuob2b.bean.AdvertList;
import com.example.zhangxin.myhuatuob2b.bean.Deadline;
import com.example.zhangxin.myhuatuob2b.bean.Home1Data;
import com.example.zhangxin.myhuatuob2b.bean.Home6Data;
import com.example.zhangxin.myhuatuob2b.bean.Home7Data;
import com.example.zhangxin.myhuatuob2b.bean.Home8Data;
import com.example.zhangxin.myhuatuob2b.bean.HomeGoodsList;
import com.example.zhangxin.myhuatuob2b.bean.OneType;
import com.example.zhangxin.myhuatuob2b.utils.URL;
import com.example.zhangxin.myhuatuob2b.view.MyGridView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment implements View.OnClickListener {


    float downNub;
    private LinearLayout textHomeSearch;
    private Button barcodeID;
    private ViewPager viewflipper;
    private ImageView iv_category_1;
    private ImageView iv_category_2;
    private ImageView iv_category_3;
    private ImageView iv_category_4;
    private ImageView iv_category_5;
    private LinearLayout dian;
    private PullToRefreshScrollView pull_refresh_scrollview;
    private TextView tv_category_1;
    private TableRow tableRow1;
    private LinearLayout homeViwe;
    private boolean deadLineIsEnd;
    private Timer timer;
    private ArrayList<OneType> oneTypes;


    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        loadingTypeData();
        initView(view);
        return view;
    }

    private void initData() {
        timer = new Timer();
        pull_refresh_scrollview.onRefreshComplete();
        String url = URL.URL_HOME;
        RequestParams params = new RequestParams(url);
        x.http().get(params,  new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray array = jsonObject.getJSONArray("datas");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);
                        JSONObject obj = new JSONObject(object.toString());
                        if(!obj.isNull("home1")){
                            String home1Json = obj.getString("home1");
                            Home1Data bean = Home1Data.newInstanceList(home1Json);
                            View home1View = getActivity().getLayoutInflater().inflate(R.layout.tab_home_item_home1, null);

                            View ll_home_item_1_title = home1View.findViewById(R.id.ll_home_item_1_title);
                            ImageView iv_Home1Title01 = (ImageView) home1View.findViewById(R.id.iv_Home1Title01);
                            TextView textView = (TextView) home1View.findViewById(R.id.TextViewHome1Title01);
                            ImageView imageView = (ImageView) home1View.findViewById(R.id.ImageViewHome1Imagepic01);

                            if (!bean.getTitle().equals("") && !bean.getTitle().equals("null") && bean.getTitle() != null) {
                                ll_home_item_1_title.setVisibility(View.VISIBLE);
                                textView.setText(bean.getTitle());

                                if ("新品推荐".equals(bean.getTitle())) {
                                    iv_Home1Title01.setImageResource(R.mipmap.ic_home_new);

                                } else if ("限时促销".equals(bean.getTitle())) {

                                    iv_Home1Title01.setImageResource(R.mipmap.ic_home_time);
                                } else if ("推荐品牌".equals(bean.getTitle())) {

                                    iv_Home1Title01.setImageResource(R.mipmap.ic_home_brand);
                                }
                            } else {
                                ll_home_item_1_title.setVisibility(View.GONE);
                            }
                            x.image().bind(imageView,bean.getImage());
                            OnImageViewClick(imageView,bean.getType(),bean.getData());
                            homeViwe.addView(home1View);
                        }else if(!obj.isNull("deadline")){
                            String deadlineJson = obj.getString("deadline");
                            Deadline bean = Deadline.newInstanceList(deadlineJson);
                            String time = bean.getDeadline();

                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");

                            long millionSeconds = 0;
                            try {
                                millionSeconds = sdf.parse(time).getTime();
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            View tab_home_item_deadline = getActivity().getLayoutInflater().inflate(R.layout.tab_home_item_deadline, null);

                            View ll_home_deadline_title = tab_home_item_deadline.findViewById(R.id.ll_home_deadline_title);
                            ImageView iv_deadlineTitle = (ImageView) ll_home_deadline_title.findViewById(R.id.iv_deadlineTitle);
                            TextView tv_deadlineTitle = (TextView) ll_home_deadline_title.findViewById(R.id.tv_deadlineTitle);
                            ImageView iv_bg = (ImageView) tab_home_item_deadline.findViewById(R.id.iv_bg);

                            if (!bean.getTitle().equals("") && !bean.getTitle().equals("null") && bean.getTitle() != null) {
                                ll_home_deadline_title.setVisibility(View.VISIBLE);
                                tv_deadlineTitle.setText(bean.getTitle());

                                if ("新品推荐".equals(bean.getTitle())) {
                                    iv_deadlineTitle.setImageResource(R.mipmap.ic_home_new);

                                } else if ("限时折扣".equals(bean.getTitle())) {

                                    iv_deadlineTitle.setImageResource(R.mipmap.ic_home_time);
                                } else if ("推荐品牌".equals(bean.getTitle())) {

                                    iv_deadlineTitle.setImageResource(R.mipmap.ic_home_brand);
                                }
                            } else {
                                tv_deadlineTitle.setVisibility(View.GONE);
                            }
                            x.image().bind(iv_bg,bean.getImage());
                            long currentTime = System.currentTimeMillis();

                            long distanceTime = millionSeconds - currentTime;
                            if (distanceTime <= 0) {
                                deadLineIsEnd = true;
                            }

                            CustomDigitalClock remainTime = (CustomDigitalClock) tab_home_item_deadline.findViewById(R.id.remainTime);
                            remainTime.setEndTime(millionSeconds);

                            remainTime.setClockListener(new CustomDigitalClock.ClockListener() { // register the clock's listener

                                @Override
                                public void timeEnd() {
                                    deadLineIsEnd = true;
                                }

                                @Override
                                public void remainFiveMinutes() {
                                    // The clock time is remain five minutes.
                                }
                            });
                            OnImageViewClick(iv_bg,bean.getType(),bean.getData(),deadLineIsEnd);
                            homeViwe.addView(tab_home_item_deadline);
                        }else if(!obj.isNull("home7")){
                            String home7Json = obj.getString("home7");
                            JSONObject home7obj = new JSONObject(home7Json);
                            String item = home7obj.getString("item");
                            String title = home7obj.getString("title");

                            View home7View = getActivity().getLayoutInflater().inflate(R.layout.tab_home_item_home7, null);

                            ImageView iv_1 = (ImageView) home7View.findViewById(R.id.iv_1);
                            ImageView iv_2 = (ImageView) home7View.findViewById(R.id.iv_2);
                            ImageView iv_3 = (ImageView) home7View.findViewById(R.id.iv_3);


                            TextView tv_1 = (TextView) home7View.findViewById(R.id.tv_1);
                            TextView tv_2 = (TextView) home7View.findViewById(R.id.tv_2);
                            TextView tv_3 = (TextView) home7View.findViewById(R.id.tv_3);

                            TextView tv_price_1 = (TextView) home7View.findViewById(R.id.tv_price_1);
                            TextView tv_price_2 = (TextView) home7View.findViewById(R.id.tv_price_2);
                            TextView tv_price_3 = (TextView) home7View.findViewById(R.id.tv_price_3);

                            if(!item.equals("[]")){
                                ArrayList<Home7Data> home7Datas = Home7Data.newInstanceList(item);
                                if(home7Datas != null && home7Datas.size() > 0){
                                    for (int j = 0; j < home7Datas.size(); j++) {

                                        Home7Data bean = home7Datas.get(j);

                                        if (j == 0) {
                                            x.image().bind(iv_1,bean.getGoods_image());

                                            OnImageViewClick(iv_1, "goods", bean.getGoods_id());

                                            tv_price_1.setText("￥" + bean.getGoods_promotion_price());

                                            tv_1.setText(bean.getGoods_name());

//                                            if (myApplication.getLoginKey() == null || myApplication.getLoginKey().equals("")) {//价格登录后可见
//                                                tv_price_1.setText("价格登录后可见");
//                                            } else {
//                                                if (myApplication.getMember_role().equals("0")) {//显示正常价格   liubw
//                                                    tv_price_1.setText("价格认证后可见");
//                                                } else {//价格认证后可见
//
//                                                }
//                                            }


                                        } else if (j == 1) {
                                            x.image().bind(iv_2,bean.getGoods_image());

                                            OnImageViewClick(iv_2,"goods",bean.getGoods_id());

                                            tv_price_2.setText("￥" + bean.getGoods_promotion_price());

                                            tv_2.setText(bean.getGoods_name());
                                        } else if (j == 2) {
                                            x.image().bind(iv_3,bean.getGoods_image());

                                            OnImageViewClick(iv_3,"goods",bean.getGoods_id());

                                            tv_price_3.setText("￥" + bean.getGoods_promotion_price());

                                            tv_3.setText(bean.getGoods_name());
                                        }

                                    }
                                }

                            }
                            homeViwe.addView(home7View);
                        }else if(!obj.isNull("adv_list")){
                            String adv_list = obj.getString("adv_list");
                            JSONObject advObj = new JSONObject(adv_list);
                            String advItem = advObj.getString("item");
                            if(!advItem.equals("[]")){
                                ArrayList<AdvertList> advertLists = AdvertList.newInstanceList(advItem);
                                if(advertLists.size()>0&&advertLists!=null){
                                    initHeadImage(advertLists);
                                }
                            }
                        }else if(!obj.isNull("home8")){
                            String home8Obj = obj.getString("home8");
                            Home8Data home8Data = Home8Data.newInstanceList(home8Obj);
                            View home8View = View.inflate(getActivity(),R.layout.tab_home_item_home8, null);

                            ImageView iv_home8_1 = (ImageView) home8View.findViewById(R.id.iv_home8_1);
                            ImageView iv_home8_2 = (ImageView) home8View.findViewById(R.id.iv_home8_2);
                            ImageView iv_home8_3 = (ImageView) home8View.findViewById(R.id.iv_home8_3);
                            ImageView iv_home8_4 = (ImageView) home8View.findViewById(R.id.iv_home8_4);

                            x.image().bind(iv_home8_1,home8Data.getRectangle1_image());
                            x.image().bind(iv_home8_2,home8Data.getRectangle2_image());
                            x.image().bind(iv_home8_3,home8Data.getRectangle3_image());
                            x.image().bind(iv_home8_4,home8Data.getRectangle4_image());

                            OnImageViewClick(iv_home8_1,home8Data.getRectangle1_type(),home8Data.getRectangle1_data());
                            OnImageViewClick(iv_home8_2,home8Data.getRectangle2_type(),home8Data.getRectangle2_data());
                            OnImageViewClick(iv_home8_3,home8Data.getRectangle3_type(),home8Data.getRectangle3_data());
                            OnImageViewClick(iv_home8_4,home8Data.getRectangle4_type(),home8Data.getRectangle4_data());
                            homeViwe.addView(home8View);
                        }else if(!obj.isNull("home6")){
                            String home6Obj = obj.getString("home6");
                            Home6Data home6Data = Home6Data.newInstanceList(home6Obj);
                            View home6View = getActivity().getLayoutInflater().inflate(R.layout.tab_home_item_home6, null);
                            ImageView iv_left = (ImageView) home6View.findViewById(R.id.iv_left);
                            ImageView iv_right = (ImageView) home6View.findViewById(R.id.iv_right);
                            x.image().bind(iv_left,home6Data.getRectangle1_image());
                            x.image().bind(iv_right,home6Data.getRectangle2_image());

                            OnImageViewClick(iv_left,home6Data.getRectangle1_type(),home6Data.getRectangle1_data());
                            OnImageViewClick(iv_right,home6Data.getRectangle2_type(),home6Data.getRectangle2_data());
                            homeViwe.addView(home6View);


                        }else if(!obj.isNull("goods")){

                            String goods = obj.getString("goods");
                            JSONObject object1 = new JSONObject(goods);
                            String title = object1.getString("title");
                            String item = object1.getString("item");
                            if(!item.equals("[]")){
                                ArrayList<HomeGoodsList> goodsLists = HomeGoodsList.newInstanceList(item);
                                View goodsView = getActivity().getLayoutInflater().inflate(R.layout.tab_home_item_goods, null);
                                TextView textView = (TextView) goodsView.findViewById(R.id.TextViewTitle);

                                MyGridView gridview = (MyGridView) goodsView.findViewById(R.id.gridview);

                                gridview.setFocusable(false);

                                HomeGoodsMyGridViewListAdapter adapter = new HomeGoodsMyGridViewListAdapter(getActivity(),goodsLists);
                                gridview.setAdapter(adapter);

                                if (!title.equals("") && !title.equals("null") && title != null) {
                                    textView.setVisibility(View.VISIBLE);
                                    textView.setText(title);
                                } else {
                                    textView.setVisibility(View.GONE);
                                }
                                homeViwe.addView(goodsView);
                            }

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initHeadImage(ArrayList<AdvertList> advertLists) {
        HeadImageAdapter adapter = new HeadImageAdapter(getActivity(),advertLists);
        viewflipper.setAdapter(adapter);


        timer.schedule(new TimerTask() {
            int flag = 0;
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        viewflipper.setCurrentItem(flag);
                    }
                });
                flag++;
            }
        },3000,5000);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_category_1:
                interGoodsclass(0);
                Toast.makeText(getActivity(),"iv_category_1",Toast.LENGTH_SHORT).show();
                break;
            case R.id.iv_category_2:
                interGoodsclass(1);
                Toast.makeText(getActivity(),"iv_category_2",Toast.LENGTH_SHORT).show();
                break;
            case R.id.iv_category_3:
                interGoodsclass(2);
                Toast.makeText(getActivity(),"iv_category_3",Toast.LENGTH_SHORT).show();
                break;
            case R.id.iv_category_4:
                interGoodsclass(3);
                break;
            case R.id.iv_category_5:
                interGoodsclass(4);
                break;
            case R.id.barcodeID:
                Toast.makeText(getActivity(),"barcodeID",Toast.LENGTH_SHORT).show();
                break;
            case R.id.textHomeSearch:

                startActivity(new Intent(getActivity(), SearchActivity.class));
                Toast.makeText(getActivity(),"textHomeSearch",Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void interGoodsclass(int index) {
        if(oneTypes != null && oneTypes.size() > 0){
            OneType bean = oneTypes.get(index);
            if(bean != null){

                ifNOData(bean.getGc_id(), bean.getGc_name());

            }
        }
    }

    private void ifNOData(final String gc_id, final String gc_name) {
        String url = URL.URL_GOODSCLASS + "&gc_id=" + gc_id;
        RequestParams params = new RequestParams(url);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject object = new JSONObject(result);
                    JSONObject obj = object.getJSONObject("datas");
                    String array = obj.getString("class_list");
                    if (array.toString().equals("0") || array.toString().equals("null")) {

                        Intent intent = new Intent(getActivity(), GoodsListFragmentManager.class);
                        intent.putExtra("gc_id", gc_id);
                        intent.putExtra("gc_name", gc_name);
                        startActivity(intent);

                    } else {

                        Intent intent = new Intent(getActivity(), TwoTypeActivity.class);
                        intent.putExtra("gc_id", gc_id);
                        intent.putExtra("gc_name", gc_name);
                        startActivity(intent);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void OnImageViewClick(View view, String type, String data) {

        this.OnImageViewClick(view, type, data, false);
    }

    public void OnImageViewClick(View view, final String type, final String data, final boolean deadLineIsEnd) {
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //  触摸时按下
                    downNub = event.getX();
                } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    // 触摸时移动
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    //  触摸时抬起
                    if (downNub == event.getX()) {
                        if (type.equals("keyword")) {//搜索关键字
                            Intent intent = new Intent(getActivity(), GoodsListFragmentManager.class);
                            intent.putExtra("keyword", data);
                            intent.putExtra("gc_name", data);
                            startActivity(intent);
                        } else if (type.equals("special")) {//专题编号

                            if (deadLineIsEnd) {

                                Toast.makeText(getActivity(), "当前活动已结束！", Toast.LENGTH_SHORT).show();

                            } else {
//                            Intent intent = new Intent(getActivity(), SubjectWebActivity.class);
                                Intent intent = new Intent(getActivity(), SubjectActivity.class);
//                            intent.putExtra("data", Constants.URL_SPECIAL + "&special_id=" + data + "&type=html");
                                intent.putExtra("data", URL.URL_SPECIAL + "&special_id=" + data);
                                startActivity(intent);
                            }
                        } else if (type.equals("goods")) {//商品编号
                            Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                            intent.putExtra("goods_id", data);
                            startActivity(intent);
                        } else if (type.equals("url")) {//地址
                           /* Intent intent = new Intent(getActivity(), SubjectWebActivity.class);
                            intent.putExtra("data", data);
                            startActivity(intent);*/
                        }
                    }
                }
                return true;
            }
        });
    }
    private void initView(View view) {
        textHomeSearch = (LinearLayout) view.findViewById(R.id.textHomeSearch);
        dian = (LinearLayout) view.findViewById(R.id.dian);
        barcodeID = (Button) view.findViewById(R.id.barcodeID);
        iv_category_1 = (ImageView) view.findViewById(R.id.iv_category_1);
        iv_category_2 = (ImageView) view.findViewById(R.id.iv_category_2);
        iv_category_3 = (ImageView) view.findViewById(R.id.iv_category_3);
        iv_category_4 = (ImageView) view.findViewById(R.id.iv_category_4);
        iv_category_5 = (ImageView) view.findViewById(R.id.iv_category_5);
        pull_refresh_scrollview = (PullToRefreshScrollView) view.findViewById(R.id.pull_refresh_scrollview);
        viewflipper = (ViewPager) view.findViewById(R.id.viewflipper);
        homeViwe = (LinearLayout) view.findViewById(R.id.homeViewID);

        textHomeSearch.setOnClickListener(this);
        barcodeID.setOnClickListener(this);
        iv_category_1.setOnClickListener(this);
        iv_category_2.setOnClickListener(this);
        iv_category_3.setOnClickListener(this);
        iv_category_4.setOnClickListener(this);
        iv_category_5.setOnClickListener(this);

        pull_refresh_scrollview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                timer.cancel();
                initData();
            }
        });

        initData();
    }




    public void loadingTypeData(){
        String url = URL.URL_GOODSCLASS;
        RequestParams params = new RequestParams(url);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject object = new JSONObject(result);
                    JSONObject obj = object.getJSONObject("datas");
                    String json = obj.getString("class_list");
                    oneTypes = OneType.newInstanceList(json);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
